package com.yanzhiyi.user.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

/**
 * FileName: JwtUtil
 * Author:   xuan zongjun
 * Date:     2020/10/21 11:25
 * Description:JWT工具类
 */

public class JwtUtil {
    //有效期为
    public static final Long JWT_TTL = 3600000L;// 60 * 60 *1000  一个小时
    //设置秘钥明文
    public static final String JWT_KEY = "itcast";

    /**
     * 创建token
     *
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createJWT(String id, String subject, Long ttlMillis) {
        long nowMillis = System.currentTimeMillis();
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        Date now = new Date();//签名签发日期
        if (ttlMillis == null) {
            ttlMillis = JWT_TTL;
        }
        long extMillis = nowMillis + ttlMillis;
        Date extDate = new Date( extMillis );//签名过期时间

        SecretKey secretKey = generalKey();

        JwtBuilder builder = Jwts.builder()
                .setId( id )//唯一的ID
                .setSubject( subject )//主题  可以是JSON数据
                .setIssuer( "admin" )// 签发者
                .setIssuedAt( now ) //签名签发日期
                .signWith( signatureAlgorithm, secretKey )//使用HS256对称加密算法签名, 第二个参数为秘钥
                .setExpiration( extDate );//设置过期时间

        return builder.compact();

    }

    /**
     * 生成加密后的秘钥 secretKey
     *
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode( JwtUtil.JWT_KEY );
        SecretKey key = new SecretKeySpec( encodedKey, 0, encodedKey.length, "AES" );
        return key;
    }

    /**
     * 解析
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
}
